package com.zpark.shiro_jsp.controller;

import com.zpark.shiro_jsp.domain.User;
import com.zpark.shiro_jsp.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Title: UserController
 * @Description:
 * @Author : 黎基彩
 * Version: 1.0
 * create: 2021/5/31 22:21
 * desc:
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    /*用来认证身份信息*/
    @RequestMapping("/login")
   // @ResponseBody
    public String login(String username,String password){
        //获取主题对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "login";
    }
    @RequestMapping("/index")
    public String toIndex(){
        return "index";
    }


    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
/*用户注册*/
    @RequestMapping("/register")
    public String register(User user){
        try {
            userService.register(user);
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            return "register";
        }
    }
//去用户注册页面
    @RequestMapping("/toRegister")
    public String toRegister(){
            return "register";
    }
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出用户
        return "login";
    }
}
